package cn.sylinx.hbatis.ds;

import cn.sylinx.hbatis.exception.BlockException;
import cn.sylinx.hbatis.exception.ExecutingException;
import cn.sylinx.hbatis.log.GLog;

/**
 * 资源辅助类
 * 
 * @author han
 *
 */
public final class ResourceHelper {

	/**
	 * 执行资源操作
	 * 
	 * @param resourceHolder
	 *            Resource对象
	 * @param block
	 *            执行块
	 * @return O
	 */
	public static <R, O> O using(Resource<R> resourceHolder, ResourceBlock<R, O> block) {

		R resource = resourceHolder.get();

		if (resource == null) {
			GLog.error("resource is null, please check resource");
			throw new ExecutingException("没有获取到资源对象");
		}

		try {
			return block.apply(resource);
		} catch (BlockException e) {
			GLog.error("资源块执行异常：" + e.getMessage(), e);
			throw new ExecutingException("资源块执行异常，" + e.getMessage(), e);

		} finally {
			resourceHolder.close(resource);
		}
	}
}
